//ENCRIPTION.v - This is the encription hardware for project 2.
//
// Created By:	Jesse Inkpen
// Date:	18-February-2014
//
// This module has a three fixed values applied to its input port and waits
// untill a go signal to start calculating an RSA encription block
// Use the define 'BITS to set the bit size of the ENCRIPTION.v synthesis.
///////////////////////////////////////////////////////////////////////////

`define BITS 16

module RSA(
	input						clk,		// clock
	input						go,		// hardware go go go
	input	[`BITS-1:0]		m,		// message
	input	[`BITS-1:0]		e,		// exponent
	input	[`BITS-1:0]		n,		// modulous
			
	output	reg [`BITS-1:0]		r,		// post processing result
	output	reg			d		// done signal
	);
	
	reg 	[`BITS*2-1:0]	z;	// message register
	reg	[`BITS-1:0]		i;			// index
	reg	[`BITS*2-1:0]  p_old;
	reg	[`BITS*2-1:0]  p_new;
	reg	[`BITS*2-1:0]  p;
	reg	[`BITS-1:0]		exp;		//copy of exp used in modular exponentiation
	
	always @(posedge clk) 
	begin
		if (~go)
		begin							// initialization
			z 			<=  1;
			p_old		<=	m;	
			exp		<=	e;
			d			<= 0;
		end
		else
		begin
			exp		<=	exp >> 1;	
			p_new		<=	((p_old * p_old) % n);
			
			if(exp[0] == 1)
			begin
				z		<=	((z * p_old) % n);
			end
			
			p_old		<= p_new;
	
			if(exp	==	0)
			begin
				d	<= 1;
				r	<= z;
			end
		end		
	end

	

endmodule
		
		